/*********************************************************************************
 *      Copyright:  (C) 2022 zengwen<1825984037@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  database_server.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/07/22)
 *         Author:  zengwen <1825984037@qq.com>
 *      ChangeLog:  1, Release initial version on "07/07/22 21:31:32"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include "logger.h"
#include "sqlite3.h"

//open database
int open_data_sqlite (sqlite3 **db)
{
	int         ret=-1;
	int         rv=-1;
	char       *errmsg = 0;

	//打开当前路径下的serbase.db数据库标识
	ret=sqlite3_open("serbase.db",db);

	if(ret!=SQLITE_OK)
	{
		printf("Failed to open database!:%s\n",sqlite3_errmsg(*db));
		return -1;
	}
	else
	{
		printf("Open data sucessfuly!\n");
	}

	//create table
	char  *sql="CREATE TABLE IF NOT EXISTS temperature_table(\
				ID INTEGER PRIMARY KEY AUTOINCREMENT,\
				pie_ID       TEXT,\
				cur_time     TEXT,\
				temp         TEXT\
				);";

	rv=sqlite3_exec(*db,sql,NULL,NULL,&errmsg);
	if(rv!= SQLITE_OK)
	{
		printf("Create table error:%s\n",errmsg);
		sqlite3_free(errmsg);
		return -2;
	}
	printf("Table create successfully\n");

	return 0;
}

//insert data

int save_data_sqlite(sqlite3 *db, char *buf)
{
	char                *pie_ID;
	char                *cur_time;
	char                *temp;
	char                 sql_in[256];
	int                  rv=0;
	char                *errmsg=0;
	const char           s[2] = "/";//设置分隔符

	pie_ID=strtok(buf, s);//获取第一个字符串
	temp=strtok(NULL,s);
	cur_time=strtok(NULL,s);

	sprintf(sql_in, "INSERT INTO temperature_table(pie_ID, cur_time,temp) VALUES('%s', '%s','%s');", pie_ID, cur_time,temp);//构造sqlite语句

	rv=sqlite3_exec(db,sql_in,NULL,NULL,&errmsg);
	if (rv == SQLITE_OK)
	{
		printf("Insert data OK! rv=%d\n", rv);
		return 0;
	}
	else
	{
		printf("Insert data Error!%s\n", strerror(errno));
		return -2;
	}
	sqlite3_close(db);
	return 0;
}
